<?php
    /* -*- Mode: PHP5; tab-width: 4; indent-tabs-mode: nil; basic-offset: 4 -*- */

    /*********************************************************
    *            --== InArch ==--
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @version n/a
    * @since 12.10.2005
    * @copyright essentialmind.com 2005
    *
    *********************************************************/


	/**
	 * A recaptchaResponse is returned from recaptcha_check_answer()
	 */
	class recaptchaResponse {
		var $is_valid;
		var $error;
	}

    
    /***
    * Class clientNodeFolder
    ****
    * This classs represents a folder
    ****
    * @package clientNodes
    * @author Thomas Brandstaetter <tb@essentialmind.com>
    * @version n/a
    * @since 11.05.2011
    * @copyright essentialmind.com 2011
    ***/
    class clientNodeExtensibleForm extends clientNode {

        /**
         * Process inputs
         * 
         * @return void 
         **/
        public function process(){ 
        
        
	        define("RECAPTCHA_API_SERVER", "http://api.recaptcha.net");
			define("RECAPTCHA_API_SECURE_SERVER", "https://api-secure.recaptcha.net");
			define("RECAPTCHA_VERIFY_SERVER", "api-verify.recaptcha.net");

			if ( $_REQUEST['confirm'] && ((int)$_REQUEST['id']) ) {
				$this->response();
			} elseif ($_POST) {
				$this->create();
			} else {
				$this->show();
			}
        }
                
        protected function response() {
        	
        	$data = $this->db->getRow("SELECT * 
        								FROM node_extensible_form_record
        								WHERE id = " . (int)$_POST['id']);
        								
			$this->smarty->assign('data', $data);
			$this->smarty->assign('template', "extensibleformthanks");
        }
                
        protected function show() {
        
            $data = $this->db->getRow("SELECT * FROM node_extensible_form WHERE id = ".$this->object);
            $data['title'] = $this->db->getOne("SELECT title FROM objectmap WHERE nodeid = ".$this->node);

			$form = $this->smarty->preFetch(ROOT . 'templates/forms/' . $data['xml_document_file']);
			
			$mand = array('Immobilien_Art', 'Type', 'Name', 'EMail');
			
            //get actual folder data
            //assign all this stuff to smarty
            
            $this->smarty->assign('form', $form);
            $this->smarty->assign('data', $data);
            $this->smarty->assign('mand', $mand);
            $this->smarty->assign('mand_js', "\"" . join("\", \"", $mand) ."\"");
            $this->smarty->assign('captcha',$this->recaptcha_get_html($GLOBALS['_CONFIG']['publickey']));            
        }
        
        protected function create () {

			$responseData = $_POST['form'];
			$responseData ['recaptcha_challenge_field'] = $_POST['recaptcha_challenge_field'];
			$responseData ['recaptcha_response_field'] = $_POST['recaptcha_response_field'];
			
 			if (!($errors = $this->verifyData($responseData))) {
	        	foreach( $responseData as &$data) {
					$data = htmlentities($data, ENT_COMPAT, "UTF-8");
				}
				
				$xml = serialize($responseData); // no xml :)
				
				// remove possible php code injection
				$xml = preg_replace('/\{php\}/', '', $xml);
				
				$this->db->Execute("INSERT INTO node_extensible_form_record(xml_content)
										VALUES (".$this->db->qstr($xml).")");
										
				$newid = $this->db->getOne("SELECT last_value FROM node_extensible_form_record_id_seq");
				$codeset = $this->db->getOne("SELECT id FROM datatype WHERE codeset = 'extensibleFormRecord'");
				
				$pi = new pageInserter($this->db);			
				$pi->addPageMap($this->node, $newid, $codeset, "Antwort $newid");
				
				header("Location: " . $this->request . "?confirm=true&id=$newid");
				exit;				
 			} else {
 				
 				$this->smarty->assign('responseData', $responseData);
   	            $this->smarty->assign('errors', $errors);
                $this->show();
   			}
        }
                
        /**
         * set the action template
         * 
         * @return void
         **/
        public function setTemplate(){ 
            $this->setActionTemplate('extensibleform.html');
        }
        
        protected function verifyData($data) {
        
        	$mands = array('Immobilien_Art', 'Type', 'Name', 'EMail');
        	$error = array();
        	
         	for( $i = 0; $i < count($mands); $i++) {
         		$k = $mands[$i];
         		if (!$data[$k]) 
         			$error [$k]= true;		
         	}
         	
         	//check captcha
         	$resp = $this->recaptcha_check_answer(	$GLOBALS['_CONFIG']['privatekey'],
         									$_SERVER["REMOTE_ADDR"],
         									$data["recaptcha_challenge_field"],
         									$data["recaptcha_response_field"]);
         									
         	if(!$resp->is_valid){
                $error['captcha'] = true;
            }								
        	
        	return $error;
        }
        
        
        
        /**
		 * Gets the challenge HTML (javascript and non-javascript version).
		 * This is called from the browser, and the resulting reCAPTCHA HTML widget
		 * is embedded within the HTML form it was called from.
		 * @param string $pubkey A public key for reCAPTCHA
		 * @param string $error The error given by reCAPTCHA (optional, default is null)
		 * @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
		
		 * @return string - The HTML to be embedded in the user's form.
		 */
		private function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false)
		{
			if ($pubkey == null || $pubkey == '') {
				die ("To use reCAPTCHA you must get an API key from <a href='http://recaptcha.net/api/getkey'>http://recaptcha.net/api/getkey</a>");
			}
			
			if ($use_ssl) {
						$server = RECAPTCHA_API_SECURE_SERVER;
				} else {
						$server = RECAPTCHA_API_SERVER;
				}
		
				$errorpart = "";
				if ($error) {
				   $errorpart = "&amp;error=" . $error;
				}
				return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>
		
			<noscript>
				<iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/>
				<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
				<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
			</noscript>';
		}
		

		
		/**
		  * Calls an HTTP POST function to verify if the user's guess was correct
		  * @param string $privkey
		  * @param string $remoteip
		  * @param string $challenge
		  * @param string $response
		  * @param array $extra_params an array of extra variables to post to the server
		  * @return ReCaptchaResponse
		  */
		protected function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array())
		{
			//require_once(dirname(__FILE__) . '/../recaptchaResponse.class.php');
		
			if ($privkey == null || $privkey == '') {
				die ("To use reCAPTCHA you must get an API key from <a href='http://recaptcha.net/api/getkey'>http://recaptcha.net/api/getkey</a>");
			}
		
			if ($remoteip == null || $remoteip == '') {
				die ("For security reasons, you must pass the remote ip to reCAPTCHA");
			}
		
			
			
			//discard spam submissions
			if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
					$recaptcha_response = new recaptchaResponse();
					$recaptcha_response->is_valid = false;
					$recaptcha_response->error = 'incorrect-captcha-sol';
					return $recaptcha_response;
			}
	
			$response = $this->_recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/verify",
											  array (
													 'privatekey' => $privkey,
													 'remoteip' => $remoteip,
													 'challenge' => $challenge,
													 'response' => $response
													 ) + $extra_params
											  );
	
			$answers = explode ("\n", $response [1]);
			$recaptcha_response = new recaptchaResponse();
	
			if (trim ($answers [0]) == 'true') {
					$recaptcha_response->is_valid = true;
			}
			else {
					$recaptcha_response->is_valid = false;
					$recaptcha_response->error = $answers [1];
			}
			return $recaptcha_response;

		}
		
		/**
		 * Submits an HTTP POST to a reCAPTCHA server
		 * @param string $host
		 * @param string $path
		 * @param array $data
		 * @param int port
		 * @return array response
		 */
		private function _recaptcha_http_post($host, $path, $data, $port = 80) {
		
				$req = $this->_recaptcha_qsencode ($data);
		
				$http_request  = "POST $path HTTP/1.0\r\n";
				$http_request .= "Host: $host\r\n";
				$http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
				$http_request .= "Content-Length: " . strlen($req) . "\r\n";
				$http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
				$http_request .= "\r\n";
				$http_request .= $req;
		
				$response = '';
				if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
						die ('Could not open socket');
				}
		
				fwrite($fs, $http_request);
		
				while ( !feof($fs) )
						$response .= fgets($fs, 1160); // One TCP-IP packet
				fclose($fs);
				$response = explode("\r\n\r\n", $response, 2);
		
				return $response;
		}

		/**
		 * Encodes the given data into a query string format
		 * @param $data - array of string elements to be encoded
		 * @return string - encoded request
		 */
		private function _recaptcha_qsencode ($data) {
        	$req = "";
	        foreach ( $data as $key => $value )
                $req .= $key . '=' . urlencode( stripslashes($value) ) . '&';

    	    // Cut the last '&'
        	$req=substr($req,0,strlen($req)-1);
	        return $req;
		}

    }
?>
